js获取dom元素宽高的方法 |
您所在的位置:网站首页 › 获取元素高度 js › js获取dom元素宽高的方法 |
① dom.style.width / height
这种⽅法,有⼀定局限性,只能取内联样式的宽⾼。 var d = document.getElementById('id').style.height console.log(d) ② dom.currentStyle.width / height这种⽅法,也是有⼀定局限性,不过我们三种常⽤css样式都能获取。但是只⽀持 IE ,其它浏览器不⽀持 ③ window.getComputedStyle(dom).width / height var d = document.getElementById('id') console.log( window.getComputedStyle(d).height)⽀持所有浏览器,兼容性好 ④ dom.getBoundingClientRect().width / height这种⽅法,⼀般⽤于计算元素的绝对位置,根据视窗左上⻆的点来算的。可以拿到四个元素 值: left 、 top 、 width 、 height #id{ height: 100px; width: 100px; margin-left: 20px; margin-top: 20px; } // 只支持内联样式 // var d = document.getElementById('id').style.height // console.log(d) //都支持,兼容性好 // var d = document.getElementById('id') // console.log( window.getComputedStyle(d).height) var d = document.getElementById('id') console.log(d.getBoundingClientRect()) |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |